﻿using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Web.WebView2.WinForms;
using Microsoft.Web.WebView2.Core;

namespace WebCapture
{
    public partial class MainForm1 : Form
    {

        private WebCaptureHelper? captureHelper;
        private CancellationTokenSource? globalCts;

        public MainForm1()
        {
            InitializeComponent();
            ProgressBarResize();
            InitProgressBar();
            InitializeWebViewAsync();
            SetWebViewHeight();

        }

        private void InitProgressBar()
        {
            // 在 InitializeComponent() 或窗体构造函数中
            tsProgressBar1.Minimum = 0;
            tsProgressBar1.Maximum = 100; // ⬅️ 必须 >= 100（因为进度通常 0~100）
            tsProgressBar1.Value = 0;
        }

        /// <summary>
        /// 设置 WebView 容器高度为屏幕高度的 60%
        /// </summary>
        private void SetWebViewHeight(double heightPercent = 0.6)
        {
            // 获取主屏幕工作区高度（排除任务栏）
            int screenHeight = Screen.PrimaryScreen.WorkingArea.Height;

            // 计算 60%
            int webViewHeight = (int)(screenHeight * heightPercent);

            // 应用到 Panel
            pnlMainWebView.Height = webViewHeight;

            // 可选：限制最小/最大高度
            // webViewPanel.Height = Math.Max(300, Math.Min(webViewHeight, 1000));
        }

        private async void InitializeWebViewAsync()
        {
            try
            {

                await webView.EnsureCoreWebView2Async(null);

                // 初始化截图助手
                captureHelper = new WebCaptureHelper(webView.CoreWebView2, @"C:\Temp\WebScreenshots");

                // 订阅事件
                captureHelper.OnLog += AppendLog;
                captureHelper.OnProgress += (percent, status) =>
                {
                    UpdateUI(percent, status);
                };
                captureHelper.OnCaptureComplete += (path) =>
                {
                    InvokeIfNeeded(() =>
                    {
                        MessageBox.Show($"截图已保存：\n{path}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        btnCapture.Enabled = true;
                        btnStop.Enabled = false;
                        tsProgressBar1.Visible = false;
                    });
                };
                captureHelper.OnCaptureCancelled += () =>
                {
                    InvokeIfNeeded(() =>
                    {
                        MessageBox.Show("截图已取消。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        btnCapture.Enabled = true;
                        btnStop.Enabled = false;
                        tsProgressBar1.Visible = false;
                    });
                };
                captureHelper.OnCaptureStart += () =>
                {
                    InvokeIfNeeded(() =>
                    {
                        btnCapture.Enabled = false;
                        btnStop.Enabled = true;
                        tsProgressBar1.Visible = true;
                        tsProgressBar1.Value = 0;
                        UpdateStatus("正在截图...");
                    });
                };

                // 设置默认 URL 并加载
                txtUrl.Text = "baidu.com"; // 可改为 https://www.example.com
                await LoadUrlFromTextBoxAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"WebView2 初始化失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void MainForm1_Resize(object sender, EventArgs e)
        {
            ProgressBarResize();
        }


        private void ProgressBarResize()
        {
            if (this.tsProgressBar1.AutoSize != false) this.tsProgressBar1.AutoSize = false;
            this.tsProgressBar1.Width = this.Width - this.tsLblStatus.Width - 50;
        }

        // ========== 按钮事件 ==========

        /// <summary>
        /// 开始截图按钮
        /// </summary>
        private async void btnCapture_Click(object sender, EventArgs e)
        {
            if (captureHelper == null)
            {
                MessageBox.Show("WebView2 尚未初始化完成。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                // 如果有全局 CTS，先取消旧任务（安全起见）
                globalCts?.Cancel();
                globalCts?.Dispose();

                globalCts = new CancellationTokenSource();

                // 执行截图（支持取消）
                string path = await captureHelper.CaptureFullPageAsync(globalCts.Token);
                // 结果已在 OnCaptureComplete 中处理
            }
            catch (OperationCanceledException)
            {
                // 用户取消，已在 OnCaptureCancelled 中处理，此处可不重复提示
            }
            catch (Exception ex)
            {
                MessageBox.Show($"截图过程中发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnCapture.Enabled = true;
                btnStop.Enabled = false;
            }
        }

        /// <summary>
        /// 停止截图
        /// </summary>
        private void btnStop_Click(object sender, EventArgs e)
        {
            captureHelper?.CancelCapture();
            globalCts?.Cancel();
        }

        /// <summary>
        /// 从 txtUrl 读取地址并重新加载网页
        /// </summary>
        private async void btnLoadWeb_Click(object sender, EventArgs e)
        {
            LoadUrlFromTextBoxAsync();

        }


        private void toolStripButton4_Click(object sender, EventArgs e)
        {

        }


        // ========== 辅助方法 ==========

        /// <summary>
        /// 从 txtUrl 获取 URL 并导航到该页面
        /// </summary>
        private async Task LoadUrlFromTextBoxAsync()
        {

            // 安全获取 URL（跨线程安全）
            //string inputUrl = txtUrl.Text?.Trim();
            string inputUrl = GetUrlFromToolStripTextBox();
            //MessageBox.Show(inputUrl);

            if (string.IsNullOrWhiteSpace(inputUrl))
            {
                MessageBox.Show("请输入有效的网址。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string normalized = NormalizeUrl(inputUrl);

            // 更新文本框显示标准化后的 URL
            SetUrlInToolStripTextBox(normalized);

            try
            {
                if (webView?.CoreWebView2 != null)
                {
                    // ✅ 正确方式：使用 CoreWebView2.Navigate（无 Async 后缀）
                    webView.CoreWebView2.Navigate(normalized);
                    AppendLog($"正在加载: {normalized}");
                }
            }
            catch (Exception ex)
            {
                AppendLog($"导航失败: {ex.Message}");
                MessageBox.Show($"无法打开网址：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 标准化 URL（与 WebCaptureHelper 中逻辑一致）
        /// </summary>
        private string NormalizeUrl(string input)
        {
            if (string.IsNullOrWhiteSpace(input)) return "https://www.baidu.com";

            input = input.Trim();
            if (!input.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
                !input.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
            {
                input = "https://" + input;
            }

            try
            {
                var uri = new Uri(input);
                string host = uri.Host;
                if (!host.StartsWith("www.", StringComparison.OrdinalIgnoreCase))
                {
                    host = "www." + host;
                    var builder = new UriBuilder(uri) { Host = host };
                    input = builder.Uri.ToString();
                }
            }
            catch
            {
                // 若解析失败，保留原样（或 fallback）
            }

            return input;
        }

        /// <summary>
        /// 线程安全地追加日志
        /// </summary>
        private void AppendLog(string message)
        {
            InvokeIfNeeded(() =>
            {
                txtLog.AppendText($"{DateTime.Now:HH:mm:ss} - {message}{Environment.NewLine}");
                txtLog.ScrollToCaret();
            });
        }

        /// <summary>
        /// 线程安全地更新状态标签
        /// </summary>
        private void UpdateStatus(string text)
        {
            InvokeIfNeeded(() =>
            {
                tsLblStatus.Text = text;
            });
        }

        /// <summary>
        /// 线程安全调用（避免跨线程异常）
        /// </summary>
        private void InvokeIfNeeded(Action action)
        {
            if (this.InvokeRequired)
                this.Invoke(action);
            else
                action();
        }

        private void UpdateUI(int percent, string? status)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => UpdateUI(percent, status)));
                return;
            }

            // 安全更新 UI
            tsProgressBar1.Value = Math.Max(0, Math.Min(100, percent));
            tsLblStatus.Text = status ?? "就绪";
        }

        private string GetUrlFromToolStripTextBox()
        {
            if (this.InvokeRequired)
                return (string)this.Invoke(new Func<string>(GetUrlFromToolStripTextBox));
            return txtUrl.Text?.Trim() ?? "";
        }

        private void SetUrlInToolStripTextBox(string url)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(SetUrlInToolStripTextBox), url);
                return;
            }
            txtUrl.Text = url;
        }

        private void txtUrl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                _ = LoadUrlFromTextBoxAsync(); // 注意：异步 void 仅用于事件
                e.SuppressKeyPress = true; // 阻止“叮”声
            }
        }
    }
}
